package com.jzhao.gper.spring.v3.aop;

import com.jzhao.gper.spring.v3.aop.aspect.JZAdvice;
import com.jzhao.gper.spring.v3.aop.intercept.JZMethodInvocation;
import com.jzhao.gper.spring.v3.aop.support.JZAdvisedSupport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;

public class JZJdkDynamicAopProxy implements InvocationHandler,JZAopProxy {

    private JZAdvisedSupport advised;

    public JZJdkDynamicAopProxy(JZAdvisedSupport config) {
        this.advised = config;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class targetClass = this.advised.getTargetClass();
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

        JZMethodInvocation invocation = new JZMethodInvocation(proxy, advised.getTarget(), method, args, targetClass, chain);
        return invocation.proceed();
    }

    @Override
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),this.advised.getTargetClass().getInterfaces(),this);
    }

    @Override
    public Object getProxy(ClassLoader classLoader) {
        return Proxy.newProxyInstance(classLoader,this.advised.getTargetClass().getInterfaces(),this);

    }

}
